package com.cj.core.annotation.log.aspect;

import com.cj.core.annotation.log.CustomLog;
import com.cj.core.annotation.log.context.CustomLogContext;
import org.aspectj.lang.ProceedingJoinPoint;
import java.util.logging.Logger;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CustomLogAspect {

    @Around("@annotation(logConfig)")
    public Object around(ProceedingJoinPoint joinPoint, CustomLog logConfig) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] paramNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();

        String businessId = extractBusinessId(paramNames, args, logConfig.businessIdParam());

        // 启动日志收集
        CustomLogContext.start();

        try {
            Object result = joinPoint.proceed();
            return result;
        } finally {
            // 获取并输出结构化日志
            String collectedLogs = CustomLogContext.getAndClear();
            if (!collectedLogs.isEmpty()) {
                String fullLog = String.format("%s完整输出日志信息为：%n业务id=%s%n%s",
                        logConfig.label(), businessId, collectedLogs);

                // 使用原生 logger 输出结构化日志
                Logger logger = Logger.getLogger(joinPoint.getTarget().getClass().getName());
                logger.info(fullLog);
            }

            // 停止日志收集
            CustomLogContext.stop();
        }
    }

    private String extractBusinessId(String[] paramNames, Object[] args, String paramName) {
        for (int i = 0; i < paramNames.length; i++) {
            if (paramNames[i].equals(paramName)) {
                Object value = args[i];
                return value == null ? "null" : value.toString();
            }
        }
        return "UNDEFINED";
    }
}